import React, {Component} from 'react';
import {
  Modal,
  Form,
  Input,
  Radio,
  Select,
  DatePicker,
  Popconfirm,
  Row,
  Col,
  Button,
  Icon,
  Upload,
  message
} from 'antd';
import styles from '../main.less';
import moment from 'moment'
import * as  ContractModel from '../../model/contract';
import * as  CustomerModel from '../../model/customer';
import * as  ProductModel from '../../model/product';
import * as  StockModel from '../../model/stock';
import * as PurchaseModel from '../../model/purchase';
const config = require('../../config.js');

import 'moment/locale/zh-cn';
moment.locale('zh-cn');
const FormItem = Form.Item;
const Option = Select.Option;
const dateFormat = 'YYYY-MM-DD';
var _ = require('underscore');
class _Modal extends Component {
  constructor(props) {
    super(props);
    let _orders = {}
    Array.from(props.record.orders || []).map(d => {
      d.id = d.id || 'key-' + parseInt(Math.random() * 10000)
      _orders[d.id] = d
    })

    let index_product = 0
    let products = []


    this.state = {
      products,
      visible: false,
      orders: _orders,
      mes: '',
      name: '',
      address: '',
      customer_num: '',
      record: props.record || {
        contract_num: ''
      }
    };

  }

  showModelHandler = async(e) => {
    if (e)
      e.stopPropagation();
    if (this.props.record !== null) {
      this.setState({visible: true, mes: '', name: '', address: '', customer_num: ''});
    } else {
      this.props.form.resetFields()
    }
  }

  hideModelHandler = () => {
    this.setState({visible: false, mes: '', name: '', address: '', customer_num: ''});
    this.props.form.resetFields()
  };
  handleSubmit = async(e) => {
    if(this.props.count<1){message.info('请返回选择一条商品，否则无法下采购单');return false};
    let values = this.props.form.getFieldsValue()
    let item = Object.assign({}, values);
    //先生成采购单
    //遍历生成stock
    //再更新采购单 prodcuts 和 合同的 products
    item.brand_num = _.uniq(this.props.products.map(d=>d.brand_num))
    item.customer_num=this.props.record.customer_num;
    item.contract_num = this.props.record.cnum
    let res = await PurchaseModel.addItem(item)
    let purchase = res.data.item
    let products = []
    for(let pd of this.getProducts()){
      let _item = {}
      _item.product_num = pd.product_num
      _item.product_backup = JSON.stringify(pd)
      _item.purchase_num = purchase.cnum
      _item.contract_num = purchase.contract_num
      _item.customer_num = this.props.record.customer_num
      let res = await StockModel.addItem(_item)
      let stock = res.data.item
      let components = []
      pd.components_stock.map(cm=>{
        components.push({
          cnum:stock.cnum+'-'+cm.index,
          name:cm.name ,
          status:'waitSendInput'
        })
      })
      await StockModel.updateByNum(stock.cnum,{components})
      products.push({
        stock_num:stock.cnum,product_num:pd.product_num
      })
    }
    await PurchaseModel.updateByNum(purchase.cnum,{products,status:'inPay'})
    let contract_products = []
    this.props.record.products.map(pd=>{ //这是销售合同的的pd 和  采购pd是不一样的
       let stocks = products.filter(purchase_pd=>purchase_pd.product_num===pd.product_num)
       let contract_product = Object.assign({},pd,{stocks})
       if(stocks.length > 0 ){
         contract_product.status = 'purchased'
       }
       contract_products.push(contract_product)
    })
    await ContractModel.updateByNum(this.props.record.cnum,{products:contract_products})
    this.props.updateList()
    this.hideModelHandler()

  };
  getProducts(){
    let products = []
    let index_product = 0
    this.props.products.map(pd=>{
      _.range(parseInt(pd.quantity||1)).map(i=>{
        let item = Object.assign({},pd)
        item.index = ++index_product
        products.push(item)
      })
    })
    products.map(pd=>{
      let components = []
      let index = 0
      pd.components.map(cm=>{
        _.range(parseInt(cm.quantity||1)).map(i=>{
          let it = Object.assign({},cm)
          it.index = ++index
          components.push(it)
        })
      })
     pd.components_stock = components
    })
    return products
  }
  render() {
    const {getFieldDecorator, getFieldValue} = this.props.form;
    const formItemLayout = {
      labelCol: {
        span: 6
      },
      wrapperCol: {
        span: 14
      }
    };
    //数量转成实物单位

    let products = this.getProducts()
    return (
      <span>
        <span onClick={this.showModelHandler}>
          {this.props.children}
        </span>
        <Modal title={'cnum' in this.state.record
          ? '修改：' + this.state.record.cnum
          : '新建一条采购单信息'} visible={this.state.visible} onCancel={this.hideModelHandler} onOk={this.handleSubmit} width="80%">
          <div>
            <table><tbody><tr><th>序号</th><th>产品编号</th>
                    <th>品牌</th>
                      <th>产品名字</th>
                    <th>产品型号</th>
                    <th>图片</th>
                  <th>原价</th>
                  <th>折扣</th>
                  <th>合同售价</th>
                  <th>部件列表</th>
                <th></th></tr>
            {products.map(pd=><tr key={pd.index}>
              <td>{pd.index}</td>
              <td>{pd.cnum}</td>
              <td>{pd.brand_num}</td>
              <td>{pd.name}</td>
              <td>{pd.model}</td>
              <td><img style={{width:"50px",heigth:"50px"}} src={config.host+'/file/'+pd.pic}/></td>
              <td>{pd.origin_money}</td>
              <td>{pd.discount}</td>
              <td>{pd.contract_money}</td>
              <td>{pd.components_stock.map(cs=><div key={cs.index}>({cs.index}) {cs.name}</div>)}</td>
            </tr>
            )}
            </tbody>
              </table>
          </div>
          <Form layout="horizontal">
            <FormItem className={styles.FormItem} {...formItemLayout} label="采购专员">
              {getFieldDecorator('purchase_user', {
                initialValue: this.state.record.purchase_user,
                rules: [
                  {
                    required: true,
                    message: '必须填写'
                  }
                ]
              })(<Input size="small"/>)}
            </FormItem>
            <FormItem className={styles.FormItem} {...formItemLayout} label="采购经理">
              {getFieldDecorator('purchase_master', {
                initialValue: this.state.record.purchase_master,
                rules: [
                  {
                    required: true,
                    message: '必须填写'
                  }
                ]
              })(<Input size="small"/>)}
            </FormItem>
            <FormItem className={styles.FormItem} {...formItemLayout} label="线下合同编号" hasFeedback>
              <Input size="small" disabled={true} defaultValue={this.props.record.offline_num}/>
            </FormItem>

            <FormItem className={styles.FormItem} {...formItemLayout} label="采购币种">
              {getFieldDecorator('currency_num', {
                initialValue: this.state.record.currency_num,
                rules: [
                  {
                    required: true,
                    message: '必须选择'
                  }
                ]
              })(
                <Radio.Group size="small">
                  {['美元', '欧元', '人民币'].map(v =>< Radio key = {
                    v
                  }
                  value = {
                    v
                  } > {
                    v
                  } < /Radio>)}
                </Radio.Group>
              )}
            </FormItem>
            <FormItem className={styles.FormItem} {...formItemLayout} label="下单日期">
              {getFieldDecorator('order_at', {
               initialValue: moment(new Date(), 'YYYY-MM-DD')})(<DatePicker />)}
            </FormItem>
          </Form>
        </Modal>
      </span>
    );
  }
}

export default Form.create()(_Modal);
